package com.yunche.yunchebusiness.ui.activity.main

import android.annotation.SuppressLint
import com.afollestad.materialdialogs.MaterialDialog
import com.alibaba.fastjson.JSONObject
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.base.BaseActivity
import com.yunche.yunchebusiness.base.rx.SchedulerUtils
import com.yunche.yunchebusiness.common.CommonDialog
import com.yunche.yunchebusiness.common.Constant
import com.yunche.yunchebusiness.network.RequestJson
import com.yunche.yunchebusiness.network.RetrofitManager
import com.yunche.yunchebusiness.network.exception.ErrorStatus
import com.yunche.yunchebusiness.network.exception.ExceptionHandle
import com.yunche.yunchebusiness.utils.SpHelper
import com.yunche.yunchebusiness.utils.ToastyUtils
import kotlinx.android.synthetic.main.activity_change_pwd.*
import okhttp3.RequestBody

class ChangePwdActivity : BaseActivity() {
    override fun setLayout(): Int = R.layout.activity_change_pwd

    override fun initView() {
    }

    override fun initData() {

    }

    @SuppressLint("CheckResult")
    private fun changePwd(requestBody: RequestBody) {
        CommonDialog.showLoading(mContext!!, Constant.Loading)
        RetrofitManager.service.changePwd(requestBody).compose(SchedulerUtils.ioToMain())
            .subscribe({
                CommonDialog.cancle()
                if (it.resultCode == ErrorStatus.SUCCESS) {

                    MaterialDialog.Builder(mContext!!)
                        .title("修改密码成功")
                        .content("请重新登录")
                        .positiveText("确定")
                        .onPositive { _, _ ->
                            SpHelper.clearPreference()
                            openActivity(LoginActivity::class.java)
                            finish()
                        }
                        .cancelable(false)
                        .show()


                } else {
                    ToastyUtils.showError(it.message!!)
                }
            }, {
                CommonDialog.cancle()
                ToastyUtils.showError(ExceptionHandle.handleException(it))
            })
    }

    override fun initEvent() {
        btn_change_pwd.setOnClickListener {

            var oldPwd = et_old_pwd.text.toString()
            var newPwd = et_new_pwd.text.toString()
            var newpwd2 = et_new_pwd_confirm.text.toString()

            if (newPwd.isEmpty() || newPwd != newpwd2) {
                ToastyUtils.showWarning("两次密码输入不一致")
                return@setOnClickListener
            }
            if (!oldPwd.isNotEmpty()) return@setOnClickListener

            var para = JSONObject()
            para["password"] = oldPwd
            para["newPassword"] = newPwd
            para["subPassword"] = newpwd2
            changePwd(RequestJson.getRequestBody(para.toJSONString()))
        }
    }

}
